<template>
  <div>
    <el-button type="primary" size="small" style="margin-left: 3px" @click="addNewReg()">
      <el-icon>
        <Edit/>
      </el-icon> &nbsp;挂号
    </el-button>

    <el-button type="primary" size="small" style="margin-left: 3px" @click="clear()">
      <el-icon>
        <Refresh/>
      </el-icon>&nbsp;清空
    </el-button>

    <br><br>
    <div style="font-size:15px;font-family:'Microsoft YaHei'">挂号信息</div>&nbsp;
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">病 历 号 :</span>&nbsp;
          <el-input placeholder="输入病历号" style="width: 110px" again="left" size="small"
                    v-model="formData.casenumber"
                    @blur="blhcx()">
          </el-input>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</span>&nbsp;
          <el-input placeholder="输入姓名" style="width: 110px" again="left" size="small"
                    v-model="formData.realname">
          </el-input>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>&nbsp;
          <el-select placeholder="选择性别" style="width: 110px" size="small" v-model="formData.gender">
            <el-option
                v-for="item in sexData"
                :key="item.id"
                :label="item.sexname"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;龄:</span>&nbsp;
          <el-input placeholder="输入年龄" style="width: 110px" again="left" size="small" v-model="formData.age">
          </el-input>
          <span style="color:red">*</span>
          <el-select placeholder="选择岁" style="width: 110px" size="small" v-model="formData.agetype">
            <el-option label="岁" value="岁"></el-option>
            <el-option label="月" value="月"></el-option>
            <el-option label="天" value="天"></el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="2">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="font-size:13px;font-family:'Microsoft YaHei'">出生日期:</span>
          <el-date-picker
              @change="calculateAge"
              v-model="formData.birthdate"
              type="date"
              placeholder="出生日期" size="small" style="width: 124px" value-format="YYYY-MM-DD">
          </el-date-picker>
        </div>
      </el-col>

      <el-col :span="7">
        <div class="grid-content bg-purple">
          <span style="font-size:13px;font-family:'Microsoft YaHei'">身份证号:</span>&nbsp;&nbsp;&nbsp;
          <el-input placeholder="在此输入身份证号" style="width: 230px" size="small"
                    v-model="formData.idnumber" @blur="idNumberBlur"></el-input>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="grid-content bg-purple">
          <span style="font-size:13px;font-family:'Microsoft YaHei'">家庭住址:</span>&nbsp;
          <el-input placeholder="在此输入家庭住址" style="width: 250px" again="left" size="small"
                    v-model="formData.homeaddress">
          </el-input>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="2">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">结算类别:</span>&nbsp;
          <el-select placeholder="结算类别" style="width: 100px" size="small" v-model="formData.settleid">
            <el-option
                v-for="item in settleData"
                :key="item.id"
                :label="item.settleName"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">看诊日期:
            <el-date-picker
                v-model="formData.visitdate"
                type="date"
                placeholder="看诊日期" size="small" style="width: 125px" value-format="YYYY-MM-DD"
                @change="kzrq_select()">
            </el-date-picker>
          </span>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">午别:</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
          <el-select placeholder="午别" style="width: 90px" size="small" v-model="formData.noon"
                     @change="Noon_select()">
            <el-option
                v-for="item in noonData"
                :key="item.noon"
                :label="item.noon"
                :value="item.noon">
            </el-option>
          </el-select>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">挂号科室:</span>&nbsp;
          <el-select placeholder="挂号科室" style="width: 108px" size="small" v-model="formData.deptid"
                     @change="Dept_select()">
            <el-option
                v-for="item in deptData"
                :key="item.id"
                :label="item.deptname"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">号&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>&nbsp;
          <el-select placeholder="号别" style="width: 100px" size="small" v-model="formData.registleid"
                     @change="RegistLe_select()">
            <el-option
                v-for="item in registrationData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">看诊医生:</span>
          <el-select placeholder="看诊医生" style="width: 110px" size="small" v-model="formData.userid"
                     @change="user_select()">
            <el-option
                v-for="item in doctorData"
                :key="item.id"
                :label="item.realName"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="2">
      <el-col :span="4">
        <div>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">病历本</span>
          <input type="checkbox" name="" v-model="formData.isbook" true-value="1" false-value="0"
                 @change="book_select()"/>
        </div>
      </el-col>

      <el-col :span="4">
        <div>
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">应收金额:</span>&nbsp;
          <el-input placeholder="应收金额" style="width: 100px" again="left" size="small" v-model="formData.fee"
                    readonly>
          </el-input>
        </div>
      </el-col>

      <el-col :span="4">
        <div>
          <span style="color:red">*</span>
          <span style="font-size:13px;font-family:'Microsoft YaHei'">收费方式:</span>&nbsp;
          <el-select placeholder="收费方式" style="width: 100px" size="small" v-model="formData.feetype">
            <el-option
                v-for="item in feetypeData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import service from '@/utils/request'
import {useCounterStore} from "@/stores/counter.js";
import {ElMessage} from "element-plus";

const counter = useCounterStore();
let formData = ref({})

let sexData = ref([{id:1,sexname:'男'},{id:2,sexname:'女'}])
let deptData = ref([])
let doctorData = ref([])
let feetypeData = ref([
  {id: 1, name: '现金'},
  {id: 2, name: '医保卡'},
  {id: 3, name: '银行卡'},
  {id: 4, name: '信用卡'},
  {id: 5, name: '微信'},
  {id: 6, name: '支付宝'},
  {id: 7, name: '云闪付'},
  {id: 8, name: '其它'}]) // 收费方式
let settleData = ref([{id: 1, settleName: '自费'}, {id: 2, settleName: '市医保'}]) // 结算类别
let noonData = ref([{noon: "上午"}, {noon: "下午"}]) // 午别
let registrationData = ref([{id: 1, name: '专家号', type: 1}, {id: 2, name: '普通号', type: 2}]) // 号别

// 身份证号失去焦点时自动填充信息
function idNumberBlur() {
  const idNumber = formData.value.idnumber;
  if (!idNumber || idNumber.length !== 18) return;

  // 提取出生日期
  const birthDateStr = idNumber.substring(6, 14);
  const birthDate = `${birthDateStr.substring(0, 4)}-${birthDateStr.substring(4, 6)}-${birthDateStr.substring(6, 8)}`;
  formData.value.birthdate = birthDate;
  calculateAge();

  // 提取性别 (第17位，奇数男，偶数女)
  const genderCode = parseInt(idNumber.substring(16, 17));
  // formData.value.gender = genderCode % 2 === 1 ? '1' : '2'; // 假设1是男，2是女
}

// 新增挂号
function addNewReg() {
  // 验证必填字段
  if (!formData.value.casenumber || !formData.value.realname || !formData.value.gender ||
      !formData.value.age || !formData.value.settleid || !formData.value.visitdate ||
      !formData.value.deptid || !formData.value.registleid || !formData.value.userid ||
      !formData.value.feetype) {
    ElMessage.error('请填写所有必填字段');
    return;
  }

  // 设置默认值
  formData.value.registerid = counter.vo_user.value.id;
  formData.value.noon = '上午';
  formData.value.isbook = '0';
  service.post("/register/add", formData.value).then(
      res => {
        ElMessage.success('挂号成功');
        clear(); // 清空表单
      })
      .catch(error => {
        ElMessage.error('挂号失败: ' + (error.response?.data?.message || error.message));
      });
}

// 清空表单
function clear() {
  formData.value = {};
  doctorData.value = [];
}

// 科室选择变化
function Dept_select() {
  if (!formData.value.deptid) return;
  service.get("/user/getbydeptid?deptid=" + formData.value.deptid)
      .then(res => {
        doctorData.value = res.data;
        // 清空已选择的医生
        formData.value.userid = '';
      })
      .catch(error => {
        console.error("获取医生列表失败:", error);
      });
}

// 号别选择变化
function RegistLe_select() {
  if (!formData.value.registleid) return;
  const selectedRegistLe = registrationData.value.find(item => item.id === formData.value.registleid);
  if (selectedRegistLe) {
    // 根据号别类型设置费用（1:专家号 50元，2:普通号 8元）
    formData.value.fee = selectedRegistLe.type === 1 ? 50 : 8;
    // 如果选择了病历本，加收1元
    if (formData.value.isbook === '1') {
      formData.value.fee += 1;
    }
  }
}

// 病历本选择变化
function book_select() {
  const selectedRegistLe = registrationData.value.find(item => item.id === formData.value.registleid);
  const baseFee = selectedRegistLe ? (selectedRegistLe.type === 1 ? 50 : 8) : 0;
  formData.value.fee = baseFee + (formData.value.isbook === '1' ? 1 : 0);
}

// 计算年龄
function calculateAge() {
  if (!formData.value.birthdate) return;

  const birthdate = new Date(formData.value.birthdate);
  const today = new Date();

  // 计算时间差
  const timeDiff = today - birthdate;
  // 计算天数
  const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
  // 计算月数
  const monthsDiff = Math.floor(daysDiff / 30.34);
  // 计算年数
  let yearsDiff = today.getFullYear() - birthdate.getFullYear()+1;
  // 调整年数
  const monthCheck = today.getMonth() - birthdate.getMonth();
  if (monthCheck < 0 || (monthCheck === 0 && today.getDate() < birthdate.getDate())) {
    yearsDiff--;
  }

  // 确定显示类型（岁、月、天）
  let ageValue, ageType;
  if (yearsDiff >= 2) {
    ageValue = yearsDiff;
    ageType = '岁';
  } else if (monthsDiff >= 1) {
    ageValue = monthsDiff;
    ageType = '个月';
  } else {
    ageValue = daysDiff;
    ageType = '天';
  }

  // 更新显示
  formData.value.age = ageValue;
  formData.value.agetype = ageType;
}

onMounted(() => {
  // 3. 加载科室数据
  service.get("/dept/list")
      .then(res => {
        deptData.value = res.data;
      })
      .catch(error => {
        console.error("加载科室数据失败:", error);
      });

  // 设置默认号别
  if (registrationData.value.length > 0) {
    formData.value.registleid = registrationData.value[0].id;
    RegistLe_select(); // 触发费用计算
  }

});
</script>